package netty.embeddedChannel.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException;

import java.util.List;

/**
 * @描述:
 * @创建人: 涂有(tuyou_cd @ keruyun.com)
 * @创建时间: 2019-08-27
 */
public class FrameChunkDecoder extends ByteToMessageDecoder {

    private final int maxFrameLength;

    public FrameChunkDecoder(int maxFrameLength) {
        this.maxFrameLength = maxFrameLength;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int readableLength = in.readableBytes();
        if (readableLength > maxFrameLength) {
            in.clear();
            throw new TooLongFrameException();
        }
        ByteBuf newBuf = in.readBytes(readableLength);
        out.add(newBuf);
    }
}
